import axios from 'axios';

import { NextRequest, NextResponse } from 'next/server';


async function getOriginImageBlobUrl(formData: FormData)
{
    try
    {

        const res = await axios.post('https://cloud.infini-ai.com/api/maas/comfy_task_api/upload/image', formData, {
            headers: {
                'Authorization': `Bearer ${process.env.API_KEY}`,
                'Content-Type': 'multipart/form-data',
                'Accept': 'application/json',
            }
        });

        const img_id = res.data.data.image_id;
        console.log('获取img_id:', img_id);

        return img_id;

    } catch (error)
    {

        console.error('获取原图失败:', error);
        throw new Error('获取原图失败');
    }
}

export async function POST(req: NextRequest)
{
    const formData = await req.formData();
    const file = formData.get('image');
    formData.append('source_file', file);

    if (!file || !(file instanceof Blob))
    {
        return NextResponse.json({ error: '未找到上传图像' }, { status: 400 });
    }

    const arrayBuffer = await file.arrayBuffer();
    const buffer = Buffer.from(arrayBuffer);

    const imgId = await getOriginImageBlobUrl(formData);
    const base64Image = `data:image/png;base64,${buffer.toString('base64')}`;
    const payload = {
        workflow_id: 'wf-dbcegx47ipvs5r3o',
        prompt: {
            "3": {
                inputs: {
                    cfg: 8,
                    denoise: 0.88,
                    sampler_name: "dpmpp_2m",
                    scheduler: "normal",
                    seed: 847364456527417,
                    steps: 30
                }
            },
            "6": {
                inputs: {
                    speak_and_recognation: true,
                    text: "cartoon"
                }
            },
            "7": {
                inputs: {
                    speak_and_recognation: true,
                    text: "watermark, text，ghibli"
                }
            },
            "10": {
                inputs: {
                    image: imgId,
                    upload: "image"
                }
            },
            "14": {
                inputs: {
                    ckpt_name: "sdxl/dreamshaperXL_v21TurboDPMSDE.safetensors"
                }
            }
        }
    };

    try
    {
        const res = await axios.post(
            'https://cloud.infini-ai.com/api/maas/comfy_task_api/prompt',
            payload,
            {
                headers: {
                    'Authorization': `Bearer ${process.env.API_KEY}`,
                    'Content-Type': 'application/json',
                },
            }
        );


        const imgs = await findGeneratedImage(res.data.data);

        console.log('生成成功:', imgs);

        const url = Array.isArray(imgs) ? imgs[0] : imgs;
        if (!url)
        {
            return NextResponse.json({ error: '生成失败' }, { status: 500 });
        }
        return NextResponse.json({
            result: url
        });
    }
    catch (error: any)
    {
        console.error('生成失败:', error);
        return NextResponse.json(
            { error: error.response?.data || error.message },
            { status: 500 }
        );
    }

}

async function findGeneratedImage({ prompt_id, prompt_token }: { prompt_id: string, prompt_token: string })
{
    console.log("工作流iD :" + prompt_id)
    return await pollTaskStatus(prompt_id);
}
async function pollTaskStatus(prompt_id: string, interval = 5000, maxAttempts = 20)
{
    for (let i = 0; i < maxAttempts; i++)
    {
        const res = await axios.post(
            'https://cloud.infini-ai.com/api/maas/comfy_task_api/get_task_info',
            {
                comfy_task_ids: [prompt_id],
                image_post_process_cmd: "image/format,jpg/quality,Q_100",
                url_expire_period: 600,
            },
            {
                headers: {
                    'Authorization': `Bearer ${process.env.API_KEY}`,
                    'Content-Type': 'application/json',
                    'Accept': 'application/json',
                }
            }
        );

        const result = res.data.data.comfy_task_info;
        console.log('获取任务状态:', result);
        const taskInfo = result?.[0];
        if (!taskInfo) throw new Error('任务信息不存在');

        console.log(`状态：${taskInfo.status}，进度：${taskInfo.progress_num}%`);

        if (taskInfo.status === 3)
        {
            return taskInfo.final_files;
        }

        await new Promise(r => setTimeout(r, interval));
    }

    throw new Error('任务超时未完成');
}
